// 引入接口文件
import { getRegion,createApi,updateApi,deletedApi} from './merchantListServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import Cookie from 'js-cookie'
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 初始默认状态
const defultState = {
  biz: {
		queryForm: {}
  },
  regionList:[],
  modalObj:{
    visible:false,
    type:""
	},
  detail:{
		"name": "", //商家名称
		"id": "",//商品类别id
		"verifyPassword": "",//核销密码
		"regionId": "",//区域id
  },
}

// 声明module
const tmpModule = {
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          dispatch({type: `getRegion`,payload: {regionIds:[Cookie.get(config.cookie.regionId)?Cookie.get(config.cookie.regionId):'A30003439']}});
        } // end if
      }) // end listen
    },
  }, 

  // 方法列表
  effects: {
    *getRegion({ payload }, { put, call, select }) {
      try {
        let {success,rows} = yield call(getRegion, {...payload })
        if (success) {
          let regionList = rows
            regionList.forEach((item,index)=>{
      				item.value = item.regionId
      				item.label = item.regionName
      				item.key = index
            })
          yield put({ type: 'updateStore', payload: { regionList } })
        }
      } catch (e) {
      }
    },
    *addOrEditDetail({ payload }, { put, call, select }) {
        let {detail} = yield select(state => state[tmpModule.namespace])
        if(payload.actionType == 'add'){
          let params = detail
          let {success} = yield call(createApi, params)
          let {biz} = yield select(state => state[tmpModule.namespace])
          if (success) {
            message.success('新增成功')
            biz.refreshListDatas(true)
          }
        }else if(payload.actionType == 'edit'){
          let params = detail
          let {success} = yield call(updateApi, params)
          let {biz} = yield select(state => state[tmpModule.namespace])
          if (success) {
            message.success('编辑成功')
            biz.refreshListDatas(true)
          }
        }
    },
    *deleteFun({ payload }, { put, call, select }) {
        let params = payload.item.id
        let {success} = yield call(deletedApi, params)
        let {biz} = yield select(state => state[tmpModule.namespace])
        if (success) {
          message.success('删除成功')
          biz.refreshListDatas(true)
        }
    },
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
